package com.tencent.wxcloudrun.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencent.wxcloudrun.constant.WxChatCache;
import com.tencent.wxcloudrun.constant.WxChatConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 获取微信token工具类
 */
@Component
public class WeChetAccessToken {

    // http请求类
    @Autowired
    private RestTemplate restTemplate;

    public String getToken() {
        // 如果缓存中的Token过期，则请求获取Token
        if (WxChatCache.AccessToken.expiration <= System.currentTimeMillis()) {
            String url = WxChatConstant.Url.ACCESS_TOKEN_URL
                    .replace("APPID", WxChatConstant.appId)
                    .replace("APPSECRET", WxChatConstant.secret);
            System.out.println("调用的接口地址为:" + url);

            // 使用restTemplate发起Http请求
            ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
            JSONObject jsonObject = JSON.parseObject(forEntity.getBody());
            System.out.println("ResponseEntity：" + jsonObject.toString());

            Object errCode = jsonObject.get("errcode");
            if (errCode != null && "40013".equals(errCode.toString())) {
                System.out.println("不合法的APPID");
            }
            // expiration：为当前执行到此处的时间+2小时有效时间为过期时间
            WxChatCache.AccessToken.token = jsonObject.get("access_token").toString();
            WxChatCache.AccessToken.expiration = System.currentTimeMillis() + WxChatCache.TIME_TOKEN_EXPIRATION - WxChatCache.TIME_TOKEN_EXPIRATION_5;
        } else {
            // 如果没过期则使用缓存中的Token
            System.out.println("返回缓存中的token:" + WxChatCache.AccessToken.token);
        }
        return WxChatCache.AccessToken.token;
    }
}